package com.sea.task;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sea.config.SerialPortManager;
import com.sea.utils.StrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Slf4j
@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class SyncSerialPortTask {

    /**
     * 1-3
     */
    @Async
    @Scheduled(cron = "0/10 * *  * * ? ")   //每10秒执行一次
    public void task1() throws IOException, InterruptedException {

        // Step1 删除文件 - 监听会重新生成文件（确保只有一条记录）
        if (openPort()) return;

        // Step2 发送16进制功能码3的请求报文
        String hexData = "01 03 00 00 00 3F 05 DA"; // 01 - 电源柜 || 03 - 功能码 || 00 00 - 起始位置 ||  00 3F | 结束位置 || 05 DA crc16
        if (SerialPortManager.SERIAL_PORT_STATE) {
            SerialPortManager.sendSerialPortData(StrUtils.hexStringToBytes(hexData));
        }
        Thread.sleep(2000); // 暂停2秒

        String hexData2 = "01 02 00 00 00 32 F9 DF";
        if (SerialPortManager.SERIAL_PORT_STATE) {
            SerialPortManager.sendSerialPortData(StrUtils.hexStringToBytes(hexData2));
        }
        Thread.sleep(2000); // 暂停2秒

        String hexData3 = "02 03 00 00 00 3F 05 E9"; // 01 - 电源柜 || 03 - 功能码 || 00 00 - 起始位置 ||  00 3F | 结束位置 || 05 DA crc16
        if (SerialPortManager.SERIAL_PORT_STATE) {
            SerialPortManager.sendSerialPortData(StrUtils.hexStringToBytes(hexData3));
        }
        Thread.sleep(2000); // 暂停2秒

        String hexData4 = "02 02 00 00 00 32 F9 EC";
        if (SerialPortManager.SERIAL_PORT_STATE) {
            SerialPortManager.sendSerialPortData(StrUtils.hexStringToBytes(hexData4));
        }
        // Step3 SerialPortCallback.dataAvailable方法监听 - 接受响应数据
    }

    /**
     * 打开端口
     */
    private boolean openPort() throws IOException {
        File portFile = new File("port.json");
        if (!portFile.exists()) {
            return true;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String port = objectMapper.readValue(new File("port.json"), String.class);
        SerialPortManager.connectSerialPort(port);
        return false;
    }
}
